package com.jdy.haoduoai.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.activity.BaseActivity;
import com.jdy.haoduoai.enums.PlayState;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.LeAudioActionItem;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.ycsj.goldmedalnewconcept.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 互动任务
 * 
 * @author hf
 * 
 */
@SuppressLint("InflateParams")
public class MyTaskAdapter extends BaseAdapter {
  private BaseActivity mContext;
  private ArrayList<LeAudioActionItem> mList;
  private LayoutInflater mInflater;
  private boolean isEditor = false;
  private int mInteraction_id;
  private boolean mClickable;

  private OnCheckListener mOnCheckListener;

  // private final SparseArray<View> saArray = new SparseArray<View>();

  // private LeSocketManagerService bindService;

  public OnCheckListener getOnCheckListener() {
    return mOnCheckListener;
  }

  public void setOnCheckListener(OnCheckListener mOnCheckListener) {
    this.mOnCheckListener = mOnCheckListener;
  }

  public interface OnCheckListener {
    void onCheckClick();
  }

  public void setData(ArrayList<LeAudioActionItem> list) {
    mList = list;
  }

  public MyTaskAdapter(BaseActivity context, ArrayList<LeAudioActionItem> list,
                       int interaction_id, boolean clickable) {
    this.mContext = context;
    this.mList = list;
    // bindService = servicec;
    mInteraction_id = interaction_id;
    mClickable = clickable;
    mInflater = LayoutInflater.from(mContext);
    bindService();
  }

  // private final ServiceConnection conn = new ServiceConnection() {
  // @Override
  // public void onServiceDisconnected(ComponentName name) {
  //
  // }
  //
  // @Override
  // public void onServiceConnected(ComponentName name, IBinder service) {
  // SocketManageBinder binder = (SocketManageBinder) service;
  // bindService = binder.getService();
  //
  // if (bindService != null) {
  // // bindService.setDeviceStateListener(TabIndexFragment.this);
  // bindService.requestDeviceDetails();
  // }
  // }
  // };

  private void bindService() {
    new Thread() {
      @Override
      public void run() {
        SocketThreadManager.getInstance().requestDeviceDetails();
      };
    }.start();

    // Intent intent = new Intent(mContext, LeSocketManagerService.class);
    // mContext.bindService(intent, conn, Context.BIND_AUTO_CREATE);
  }



  public void setEditor(boolean iseditor) {
    this.isEditor = iseditor;
  }

  public void setSelectAll(boolean isSelectAll) {
    isEditor = true;
  }

  @Override
  public int getCount() {
    return mList.size();
  }

  public boolean isEditor() {
    return isEditor;
  }

  @Override
  public Object getItem(int position) {
    return mList.get(position);
  }

  @Override
  public long getItemId(int position) {
    return position;
  }

  int mVideoId = -1;;
  PlayState mPlayState = PlayState.None;

  public void updateWidgetStatus(int id, PlayState ps) {
    mVideoId = id;
    mPlayState = ps;
    notifyDataSetChanged();
  }

  public int getCheckedCount() {
    int count = 0;

    if (Tools.isNotEmpty(mList) && !mList.isEmpty()) {
      for (LeAudioActionItem item : mList) {
        if (item.status == 1) {
          ++count;
        }
      }
    }

    return count;

  }

  @Override
  public View getView(final int position, View convertView, ViewGroup parent) {
    final LeAudioActionItem item = mList.get(position);
    final ViewHolder holder;
    // convertView = saArray.get(position);
    if (convertView == null) {
      convertView = mInflater.inflate(R.layout.task_item, null);
      holder = new ViewHolder();
      holder.checkBox_task = (CheckBox) convertView
          .findViewById(R.id.checkBox_task);

      holder.line = convertView.findViewById(R.id.v_line);
      holder.my_task_preview = (TextView) convertView.findViewById(R.id.my_task_preview);
      holder.view = (RelativeLayout) convertView.findViewById(R.id.view);
      holder.img_check = (ImageView) convertView.findViewById(R.id.img_check);
      holder.img_check.setTag(position);
      holder.line.setTag(position);

      convertView.setTag(holder);
      // saArray.put(position, convertView);
    } else {
      holder = (ViewHolder) convertView.getTag();
    }

    LayoutParams params = (LayoutParams) holder.line.getLayoutParams();
    params.addRule(RelativeLayout.BELOW, R.id.img_pt);
    params.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.tv_helpview);

    holder.line.setLayoutParams(params);

    int pos = (int) holder.line.getTag();
    if (pos == 2) {
      holder.line.setVisibility(View.GONE);
    }

    if (item != null) {
      holder.checkBox_task.setText(item.content);
      holder.checkBox_task.setChecked(item.status == 1);

      if (mVideoId == -1) {
        holder.img_check.setBackgroundResource(R.drawable.play_blue);
      } else if (mVideoId == item.action_id) {
        holder.img_check.setBackgroundResource(R.drawable.pause_blue);
      } else {
        holder.img_check.setBackgroundResource(R.drawable.play_blue);
      }

      if (mPlayState == PlayState.None || mPlayState == PlayState.Offline
          || mPlayState == PlayState.Stop || mPlayState == PlayState.NoResource) {
        holder.img_check.setBackgroundResource(R.drawable.play_blue);
      } else {
        if (mVideoId != -1 && mVideoId == item.action_id) {
          if (mPlayState == PlayState.Playing) {
            holder.img_check.setBackgroundResource(R.drawable.pause_blue);
          } else {
            holder.img_check.setBackgroundResource(R.drawable.play_blue);
          }
        } else {
          holder.img_check.setBackgroundResource(R.drawable.play_blue);
        }
      }

      holder.img_check.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
          if (mPlayState == PlayState.None || mPlayState == PlayState.Offline
              || mPlayState == PlayState.Stop
              || mPlayState == PlayState.NoResource) {
            playvideo(mInteraction_id, position, holder.img_check);
            holder.img_check.setBackgroundResource(R.drawable.pause_blue);
          } else {
            if (mVideoId != -1 && mVideoId == item.action_id) {
              if (mPlayState == PlayState.Playing) {
                  try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("code", 202);
                    jsonObject.put("act", "ctlvideo");
                    jsonObject.put("data", "pause");
                    SocketThreadManager.getInstance().send(jsonObject.toString());
                  } catch (JSONException e) {
                    e.printStackTrace();
                  } catch (Exception e) {
                    e.printStackTrace();
                  }

                holder.img_check.setBackgroundResource(R.drawable.play_blue);
              } else {
                //if (mImHelper != null && mImHelper.isLogin()) {
                  try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("code", 202);
                    jsonObject.put("act", "ctlvideo");
                    jsonObject.put("data", "resume");
                    SocketThreadManager.getInstance().send(jsonObject.toString());
                  } catch (JSONException e) {
                    e.printStackTrace();
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                //}
                holder.img_check.setBackgroundResource(R.drawable.pause_blue);
              }
            } else {
              playvideo(mInteraction_id, position, holder.img_check);
              holder.img_check.setBackgroundResource(R.drawable.pause_blue);
            }
          }
        }
      });
    }

    holder.my_task_preview.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (onPreviewClickListener != null) {
          onPreviewClickListener.onPreviewClick(holder.my_task_preview,item.action_id, item.url);
        }
      }
    });

    holder.view.setClickable(mClickable);
    holder.checkBox_task.setTag(item);

    return convertView;
  }

  private OnPreviewClickListener onPreviewClickListener;

  public void setOnPreviewClickListener(OnPreviewClickListener onPreviewClickListener) {
    this.onPreviewClickListener = onPreviewClickListener;
  }

  private void playvideo(final int sid, final int clause_num,
      final ImageView img) {
    new CustomAsyncTask(mContext, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          img.setBackgroundResource(R.drawable.pause_blue);

          Toast.makeText(mContext, "已推送到设备播放", Toast.LENGTH_SHORT).show();
//          if (LeConfig.isDeviceConnect) {
//            Toast.makeText(mContext, "已推送到设备播放", Toast.LENGTH_SHORT).show();
//          } else {
//            img.setBackgroundResource(R.drawable.play_blue);
//            Toast.makeText(mContext, "未连接到设备，请检查设备联网情况！", Toast.LENGTH_SHORT)
//                .show();
//          }

        } else {
          if (Tools.isNotNullStr(result.data)) {
            Toast.makeText(mContext, result.data, Toast.LENGTH_SHORT).show();
          }

          img.setBackgroundResource(R.drawable.play_blue);
        }
      }

      @SuppressWarnings("unused")
      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();

        int uid = -1, volume = -1, minutes = -1;
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();

        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put(HttpUtils.TAG_ACTION_I, "play");
       // param_.put("mode", "im");
        param_.put(HttpUtils.TAG_OPERATION_I, "interaction_audio");
        param_.put("interaction_num", String.valueOf(clause_num + 1));
        // param_.put(HttpUtils.TAG_TYPE_I, "cartoon");
        if (sid != -1) {
          param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(sid));
        }
        param_.put(HttpUtils.TAG_PLAY_MODE, String.valueOf(LeConfig.PlayMode));

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
            HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();
  }

  private static class ViewHolder {
    private CheckBox checkBox_task;
    View line;
    TextView my_task_preview;
    RelativeLayout view;
    ImageView img_check;
  }

}
